import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/models/book/Options.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:intl/intl.dart';
import 'package:reactive_forms/reactive_forms.dart';
import '../../../themes/appTheme.dart';

class StudentReportBottom extends StatefulWidget {
  StudentReportBottom({
    Key? key,
    Options? this.selectedTime,
    Function? this.updateSelectedTime,
    String? this.startTime,
    String? this.endTime,
    Function? this.updateCustomTime,
    String? this.classId,
  }) : super(key: key);

  final selectedTime;
  final updateSelectedTime;
  final startTime;
  final endTime;
  final updateCustomTime;
  final classId;

  @override
  _StudentReportBottom createState() => _StudentReportBottom();
}

class _StudentReportBottom extends State<StudentReportBottom> {
  final formModel = FromAndToModel();
  late FormGroup form;

  @override
  void initState() {
    form = this.formModel.form;
    form.control('from').value = null;
    form.control('to').value = null;
    super.initState();
  }

  void _onCustomTimeUpdate() {
    Log.debug("form.valid=${form.valid} form.value=${form.value}");
    if (!form.valid) {
      form.markAllAsTouched();
      return;
    }
    var tempStartTime =
        DateFormat('MM/dd/yyyy').format(form.control("from").value);
    var tempEndTime = DateFormat('MM/dd/yyyy').format(form.control("to").value);
    widget.updateCustomTime(tempStartTime, tempEndTime);
  }

  Widget build(BuildContext context) {
    return Container(
      child: Container(
        color: Colors.transparent,
        child: Row(
          children: [
            DropdownButton(
              dropdownColor: Get.isDarkMode
                  ? AppTheme.colors.darkTheme4
                  : Get.theme.primaryColor,
              icon: Icon(Icons.arrow_drop_down_outlined, color: Colors.black),
              value: widget.selectedTime,
              items: Constants.timeRanges.map((value) {
                return DropdownMenuItem(
                  value: value,
                  child: Text(
                    value.label.toString(),
                    style: TextStyle(
                        fontSize: 15.0,
                        color: Get.isDarkMode
                            ? Get.theme.primaryColorDark
                            : Get.theme.primaryColorLight),
                    overflow: TextOverflow.fade,
                  ),
                );
              }).toList(),
              onChanged: (value) {
                value as Options;
                widget.updateSelectedTime(value);
                switch (value.value) {
                  case 0:
                    widget.updateCustomTime(null, null);
                    break;
                  case '*':
                    break;
                  default:
                    int timeDiff = (value.value == null ? 0 : value.value) * -1;
                    var tempStartTime = DateFormat('MM/dd/yyyy')
                        .format(DateTime.now().add(Duration(days: timeDiff)));
                    var tempEndTime =
                        DateFormat('MM/dd/yyyy').format(DateTime.now());
                    widget.updateCustomTime(tempStartTime, tempEndTime);
                }
                form.control('from').value = null;
                form.control('to').value = null;
              },
            ),
            widget.selectedTime.value == "*"
                ? Expanded(
                    child: ReactiveForm(
                    formGroup: form,
                    child: Row(
                      children: <Widget>[
                        Flexible(
                          flex: 1,
                          child: ReactiveTextField<DateTime>(
                            formControlName: 'from',
                            //readOnly: true,
                            decoration: InputDecoration(
                              labelText: 'From'.tr,
                              labelStyle:
                                  Theme.of(context).textTheme.titleSmall,
                              suffixIcon: ReactiveDatePicker<DateTime>(
                                formControlName: 'from',
                                firstDate: DateTime(1990),
                                lastDate: widget.endTime != null
                                    ? DateFormat('MM/dd/yyyy')
                                        .parse(widget.endTime)
                                    : DateTime.now(),
                                builder: (context, picker, child) {
                                  return IconButton(
                                    onPressed: picker.showPicker,
                                    icon: const Icon(Icons.date_range),
                                  );
                                },
                              ),
                            ),
                          ),
                        ),
                        Flexible(
                          flex: 1,
                          child: ReactiveTextField<DateTime>(
                            formControlName: 'to',
                            //readOnly: true,
                            decoration: InputDecoration(
                              labelText: 'To'.tr,
                              labelStyle:
                                  Theme.of(context).textTheme.titleSmall,
                              suffixIcon: ReactiveDatePicker<DateTime>(
                                formControlName: 'to',
                                firstDate: widget.startTime != null
                                    ? DateFormat('MM/dd/yyyy')
                                        .parse(widget.startTime)
                                        .add(const Duration(days: 1))
                                    : DateTime(1990),
                                lastDate: DateTime.now(),
                                builder: (context, picker, child) {
                                  return IconButton(
                                    onPressed: picker.showPicker,
                                    icon: const Icon(Icons.date_range),
                                  );
                                },
                              ),
                            ),
                          ),
                        ),
                        ReactiveFormConsumer(
                          builder: (context, form, child) {
                            return ElevatedButton(
                                child: Text('Go'.tr),
                                onPressed: _onCustomTimeUpdate);
                          },
                        ),
                      ],
                    ),
                  ))
                : Text(""),
            Expanded(
                child: widget.startTime != null && widget.endTime != null
                    ? Text(
                        "  ** Showing report from ${widget.startTime}(UTC) to ${widget.endTime}(UTC)")
                    : Text(""))
          ],
        ),
      ),
    );
  }
}
